<template>
  <div v-if="show">
    <wxc-result type="errorPage"
      :show="show"
      padding-top="232"></wxc-result>
  </div>
  <div v-else>
    <router-view/>
  </div>
</template>

<style>
  @import '//at.alicdn.com/t/font_1027552_258bb6rsaye.css';
</style>

<style lang="scss">
  @import './assets/styles/reset.scss';
</style>

<script>
import Qs from 'qs'
import uuidv1 from 'uuid/v1'
import { uuidLogin, userInfo } from '@/api/user'
import { getKey } from '@/api/key'
import { WxcResult } from 'weex-ui'

export default {
  components: {
    WxcResult
  },
  data: () => ({
    merchantId: '',
    show: false,
    defaultLang: 1
  }),
  created () {
    if (!localStorage.getItem('language')) localStorage.setItem('language', this.defaultLang)

    this.getMerchantId()
    this.getKey()

    this.userInfo()

    if (!localStorage.getItem('token')) this.uuidLogin()
  },
  methods: {
    getMerchantId () {
      this.merchantId = this.$route.query.mid ? this.$route.query.mid : localStorage.getItem('merchant_id')
      if (!this.merchantId) this.show = true
    },
    getKey () {
      getKey({ system_type: 1 }).then(res => {
        localStorage.setItem('key', res.data.key)
        localStorage.setItem('timestamp', res.data.timestamp)
        localStorage.setItem('system_type', res.data.system_type)
      }).catch(err => {
        console.log(err.message)
      }).finally(() => {})
    },
    uuidLogin () {
      let data = Qs.stringify({
        system_type: localStorage.getItem('system_type'),
        timestamp: localStorage.getItem('timestamp'),
        key: localStorage.getItem('key'),
        uuid: uuidv1()
      })
      uuidLogin(data).then(res => {
        localStorage.setItem('token', res.data.token)
      }).catch(err => {
        console.log(err.message)
      }).finally(() => {})
    },
    userInfo () {
      userInfo({
        system_type: localStorage.getItem('system_type'),
        timestamp: localStorage.getItem('timestamp'),
        key: localStorage.getItem('key'),
        token: localStorage.getItem('token')
      }).then(res => {
      }).catch(err => {
        this.uuidLogin()
        console.log(err.message)
      }).finally(() => {})
    }
  }
}
</script>
